package com.attilax.device;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.attilax.asyn.AsynUtil;
import com.attilax.cmd.CmdX;
import com.attilax.collection.list;
import com.attilax.concur.TaskUtil;
import com.attilax.dataspider.BusPart;
import com.attilax.dataspider.MyThreadFactory;
import com.attilax.dataspider.TsaolyoNetDataSpider;
import com.google.common.collect.Lists;

public class CpuUtil {

	public static void main(String[] args) throws CantGetData {
		 while (true) {
		 CpuUtil cpuUtil = new CpuUtil();
		 int avg = cpuUtil.getCpuRate_avg();
		 System.out.println("avg:" + String.valueOf(avg) + "  now:"
		 + cpuUtil.cpu_now);
		 TaskUtil.sleep(1000);
		 }

//		long longstart = System.currentTimeMillis();
//		System.out.println(getCpuRate());
//		long end = System.currentTimeMillis();
//		System.out.println("--time(ms):" + (end - longstart));
	}

	public static final Logger logger = LoggerFactory
			.getLogger(TsaolyoNetDataSpider.class);

	public static Integer getCpuRate_retNull() {
		try {
			return getCpuRate();
		} catch (CantGetData e) {
			return null;
		}
	}

	public static int getCpuRate() throws CantGetData {
		String getCpuRate = "wmic cpu get LoadPercentage";
		String ret = CmdX.exec(getCpuRate);
		logger.info("--wmic cpu:" + ret);
		String[] a = ret.split("\n");
		List<String> li = Lists.newArrayList();
		for (String string : a) {
			String line = string.trim();
			if (line.length() == 0)
				continue;
			li.add(line);
		}
		String cpu = null;
		if (li.size() == 1)
			throw new CantGetData(ret);
		// String cpu = li.get(li.size() - 1);
		// try {
		cpu = li.get(1).toString().trim();

		// } catch (Exception e) {
		// throw new
		// }

		return Integer.parseInt(cpu.toString());
	}

	public static Calcor ccr = new Calcor(1000);

	int def = 85;
	Integer cpu_now;
	public static ExecutorService es = Executors.newFixedThreadPool(10,
			new MyThreadFactory("get_cpu_pool"));

	// Executors.newFixedThreadPool(10);
	public Integer getCpuRate_avg() {
		Runnable ra = () -> {
			try {
				cpu_now = getCpuRate();
				ccr.setInfo(cpu_now);

			} catch (CantGetData e) {

				ccr.setInfo(def);
			}
		};
		es.execute(ra);
		// TaskUtil.asyn(ra, "getCpuRate_avg");

		// if(ccr!=null)
		return ccr.getInt();
		// return -1;
	}

	// int bus_freq = 50;

	List<BusPart> busParts = Lists.newArrayList();

	public void addPart(BusPart taskPool) {
		busParts.add(taskPool);

	}

}
